/* http://www.cnblogs.com/youring2/archive/2012/07/13/2590010.html 文档参考*/
var swfu;
/* 报错信息添加 */
var isError = true;
var fileNum = 0;
var successNum = 0;
//上传成功后，要把图片地址放到textarea显示
var taObject;
var Uploader = {
    getFileSize: function(num) {
        if (isNaN(num)) {
            return false;
        }
        num = parseInt(num);
        var units = [" B", " KB", " MB", " GB"];
        for (var i = 0; i < units.length; i += 1) {
            if (num < 1024) {
                num = num + "";
                if (num.indexOf(".") != -1 && num.indexOf(".") != 3) {
                    num = num.substring(0, 4);
                } else {
                    num = num.substring(0, 3);
                }
                break;
            } else {
                num = num / 1024;
            }
        }
        return num + units[i];
    },
    updateStatus: function(fileId, html) {
        $("#file_tr_" + fileId).get(0).cells[2].innerHTML = html;
    },
    updateOpt: function(fileId, html) {
        $("#file_tr_" + fileId).get(0).cells[3].innerHTML = html;
    },
    Handler: {
        fileQueued: function(file) {
            $("#photo-uploader-files-list").append("<tr id='file_tr_" + file.id + "'><td>" + file.name + "</td><td>" + Uploader.getFileSize(file.size) + "</td><td>等候上传</td><td class='opt'><a href='javascript:void(0);' onclick='cancelFile(\"" + file.id + "\");'>删除</a></td></tr>");
        },
        fileDialogComplete: function(num, s_num, total) {
            fileNum = total;//将添加文件的总数赋值给fileNum
        },
        uploadComplete: function(file) {
            //递归实现自动批量上传
            this.startUpload();
        },
        uploadStart: function(file) {
            //开始上传此文件
            Uploader.updateStatus(file.id, "开始上传");
        },
        uploadProgress: function(file, bytesLoaded, bytesTotal) {
            var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
            Uploader.updateStatus(file.id, percent + "%");
        },
        uploadSuccess: function(file, serverData) {
            var data = eval("(" + serverData + ")");
            if (data.status == 0) {
                //Uploader.updateStatus(file.id, data.dest_file_name);调试代码
                Uploader.updateStatus(file.id, "上传失败");
            } else {
                Uploader.updateStatus(file.id, "上传完毕");
                Uploader.updateOpt(file.id, "<a href='" + data.dest_file_name + "' target='_blank'>查看文件</a>");
                taObject.success(data);
                successNum++;
            }
            if (successNum == fileNum) {
                isError = false;
                $("#myMutiModal").find(".close").click();
                $(".muti-upload-js").remove();
                taObject.allSuccess();
            } else {
                isError = true;
            }
        },
        fileQueueError: function(file, errorCode, message) {
            alert(file.name + " : " + '文件不符合要求，可上传文件大小为300KB以内 ,文件类型为jpg;jpeg;gif;png');
            console.log(file);
            console.log(errorCode);
            console.log(message);
        }
    }
};

$(function() {
    swfu = new SWFUpload({
        //debug:true,
        upload_url: '/admin/upload/mulitpics/', //上传文件的地址
        //post_params: {'admin_sso' : $.cookie("admin_sso")},
        flash_url: "/admin_resources/our/swfupload/swfupload.swf",
        file_size_limit: '300KB', //可选择文件的大小，用户可以选择的文件大小，有效的单位有B、KB、MB、GB，若无单位默认为KB
        file_types: '*.jpg;*.jpeg;*.gif;*.png;', //限制上传的文件类型，这个是非常有用且重要的，默认值为*.*  如果只需图片类型：*.jpg;*.jpeg;*.gif;*.png;*.bmp;
        file_types_description: "All Image Files",
        file_post_name: "upload_image_file", //后端$_FILES的数组名，$_FILES['file']['tmp_name']
        button_placeholder_id: "spanSWFUploadButton", //选择文件按钮占位符的id
        button_width: 60, //选择文件按钮的各个样式参数值
        button_height: 20,
        button_text: "<b>添加文件</b>",
        button_text_left_padding: 3,
        button_text_top_padding: 2,
        button_cursor: SWFUpload.CURSOR.HAND,
        //handler 监听事件
        file_queued_handler: Uploader.Handler.fileQueued, //当一个文件被成功添加时触发
        file_queue_error_handler: Uploader.Handler.fileQueueError, //文件添加失败时触发
        file_dialog_complete_handler: Uploader.Handler.fileDialogComplete, //当文件选择完后，可在此步设置自动上传(本案例没有设置自动上传)
        upload_complete_handler: Uploader.Handler.uploadComplete, //当上传队列中的一个文件完成了一个上传周期，无论是成功(uoloadSuccess触发)还是失败(uploadError触发)，uploadComplete事件都会被触发，这也标志着一个文件的上传完成，可以进行下一个文件的上传了
        upload_start_handler: Uploader.Handler.uploadStart, //开始上传此文件
        upload_progress_handler: Uploader.Handler.uploadProgress, //上传文件的过程中触发，可用来显示进度
        upload_success_handler: Uploader.Handler.uploadSuccess
    });
});

//删除队列中的文件
function cancelFile(id) {
    swfu.cancelUpload(id, false);
    $("#file_tr_" + id + " td:eq(2)").text("已取消");
    $("#file_tr_" + id + " td:eq(3)").text("");
    fileNum--;
}